package lib.self.util.autoFit;

import android.content.Context;

import lib.self.ConstEx;
import lib.self.bean.Screen;

/**
 * description: 专门用于适配分辨率, 根据dp来设置的
 * author: Steven Xiao
 * date: 2017/4/24
 */
public class FitDpUtil {

    public static final float KMaxScreenWidth = 1080;
    public static final float KMaxScreenHeight = 1920;

    public static final int KDpBaseScale = 3;

    private static float mScaleResolution = ConstEx.KInvalidValue;
    private static float mDensity = ConstEx.KInvalidValue;

    /**
     * 获取缩放比例
     *
     * @param context
     * @return
     */
    public static float getScale(Context context) {
        if (mScaleResolution == ConstEx.KInvalidValue) {
            Screen screen = new Screen(context);

            float scaleW;
            float scaleH;

            if (screen.mWidth > screen.mHeight) {
                //横屏
                scaleW = screen.mWidth / KMaxScreenHeight;
                scaleH = screen.mHeight / KMaxScreenWidth;
            } else {
                //竖屏
                scaleW = screen.mWidth / KMaxScreenWidth;
                scaleH = screen.mHeight / KMaxScreenHeight;
            }
            mScaleResolution = screen.mWidth <= screen.mHeight ? scaleW : scaleH;
        }
        return mScaleResolution;
    }

    /**
     * 获取屏幕密度
     */
    public static float getDensity(Context context) {
        if (mDensity == ConstEx.KInvalidValue) {
            Screen screen = new Screen(context);
            mDensity = screen.mDensity;
        }
        return mDensity;
    }

    /**
     * 根据缩放比例将dp转换成px
     *
     * @return
     */
    public static int dpToPx(float dp, Context context) {
        return (int) (dp * KDpBaseScale * getScale(context));
    }

    /**
     * 将经过density绽放的px值转换成scale后的px
     *
     * @param px
     * @param context
     * @return
     */
    public static float densityPxToScalePx(float px, Context context) {
        px /= getDensity(context);
        px *= KDpBaseScale;
        px *= getScale(context);
        return px;
    }

    /**
     * 将dp转成px 兼容办法--未做适配
     */
    public static int dp2px(float dp, Context context) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dp * scale + 0.5f);
    }
}
